﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace LightingPlatform.TCP
{
    internal class ProtocolEncoder
    {
        public byte[] Encode(ProtocolData protocolData)
        {
            byte[] header = new byte[6];
            header[0] = (byte)(protocolData.CommandID >> 8);
            header[1] = (byte)(protocolData.CommandID >> 0);
            header[2] = (byte)(protocolData.SerialNumber >> 24);
            header[3] = (byte)(protocolData.SerialNumber >> 16);
            header[4] = (byte)(protocolData.SerialNumber >> 8);
            header[5] = (byte)(protocolData.SerialNumber >> 0);

            MemoryStream stream = new MemoryStream();
            stream.WriteByte(ProtocolData.Head);
            for (int i = 0; i < header.Length; i++)
            {
                this.Write(stream, header[i]);
            }

            for (int i = 0; i < protocolData.Data.Length; i++)
            {
                this.Write(stream, protocolData.Data[i]);
            }

            stream.WriteByte(ProtocolData.Tail);
            return stream.ToArray();
        }

        private void Write(MemoryStream stream, byte value)
        {
            switch (value)
            {
                case ProtocolData.Head:
                    stream.WriteByte(ProtocolData.HeadEscape);
                    stream.WriteByte(ProtocolData.HeadEscape1);
                    break;
                case ProtocolData.HeadEscape:
                    stream.WriteByte(ProtocolData.HeadEscape);
                    stream.WriteByte(ProtocolData.HeadEscape2);
                    break;
                case ProtocolData.Tail:
                    stream.WriteByte(ProtocolData.TailEscape);
                    stream.WriteByte(ProtocolData.TailEscape1);
                    break;
                case ProtocolData.TailEscape:
                    stream.WriteByte(ProtocolData.TailEscape);
                    stream.WriteByte(ProtocolData.TailEscape2);
                    break;
                default:
                    stream.WriteByte(value);
                    break;
            }
        }
    }

}
